package com.base.git;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.transport.RemoteRefUpdate;

import java.io.File;
import java.util.Collection;

public class GitPushDemo {

    public static void main(String[] args) {
        // 本地仓库路径
        String localPath = "D:\\java\\work\\base-demo";
        // 远程仓库URL
        String remoteUrl = "https://gitee.com/xuyou551/base-demo.git";
        // 用户名
        String username = "179647302@qq.com";
        // 密码或访问令牌
        String password = "xu123123";

        try (Repository repository = Git.open(new File(localPath)).getRepository()) {
            // 创建 Git 对象
            Git git = new Git(repository);

            // 获取远程仓库
            URIish uri = new URIish(remoteUrl);
            
            // 设置 PushCommand
            PushCommand pushCmd = git.push();
            pushCmd.setRemote(uri.toASCIIString());
            pushCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            
            // 执行 push
            Iterable<PushResult> results = pushCmd.call();

            // 处理 push 结果
            for (PushResult result : results) {
                System.out.println(result.getRemoteUpdates());
                result.getRemoteUpdates().forEach(item -> {
                    if (item.getStatus() == RemoteRefUpdate.Status.OK) {
                        System.out.println("Push successful!");
                    } else {
                        System.out.println("Push failed: " + item.getStatus());
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}